{% extends 'base.html' %}
{% load static %}

{% block title %}分析报告 - CFS Web System{% endblock %}

{% block page_type %}analytics-reports{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item"><a href="{% url 'analytics:dashboard' %}">数据分析</a></li>
<li class="breadcrumb-item active">分析报告</li>
{% endblock %}

{% block content %}
<!-- 报告生成器 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-line me-2"></i>报告生成器
                    </h6>
                    <button type="button" class="btn btn-primary" onclick="generateReport()">
                        <i class="fas fa-play"></i> 生成报告
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form id="report-form" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">报告类型</label>
                        <select class="form-select" id="report-type" name="report_type" onchange="updateReportOptions()">
                            <option value="summary">系统概览</option>
                            <option value="usage">使用统计</option>
                            <option value="performance">性能分析</option>
                            <option value="error">错误分析</option>
                            <option value="custom">自定义报告</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">时间范围</label>
                        <select class="form-select" id="time-range" name="time_range" onchange="updateDateRange()">
                            <option value="today">今天</option>
                            <option value="yesterday">昨天</option>
                            <option value="week" selected>最近7天</option>
                            <option value="month">最近30天</option>
                            <option value="quarter">最近90天</option>
                            <option value="custom">自定义</option>
                        </select>
                    </div>
                    <div class="col-md-2" id="start-date-container">
                        <label class="form-label">开始日期</label>
                        <input type="date" class="form-control" id="start-date" name="start_date">
                    </div>
                    <div class="col-md-2" id="end-date-container">
                        <label class="form-label">结束日期</label>
                        <input type="date" class="form-control" id="end-date" name="end_date">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">输出格式</label>
                        <select class="form-select" id="output-format" name="output_format">
                            <option value="html">HTML</option>
                            <option value="pdf">PDF</option>
                            <option value="excel">Excel</option>
                            <option value="csv">CSV</option>
                        </select>
                    </div>
                    <div class="col-md-1">
                        <label class="form-label">&nbsp;</label>
                        <button type="button" class="btn btn-outline-secondary w-100" onclick="previewReport()">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </form>
                
                <!-- 自定义报告选项 -->
                <div id="custom-options" class="mt-3" style="display: none;">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">包含模块</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="include-files" name="include_modules" value="files" checked>
                                <label class="form-check-label" for="include-files">文件管理</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="include-tasks" name="include_modules" value="tasks" checked>
                                <label class="form-check-label" for="include-tasks">任务处理</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="include-templates" name="include_modules" value="templates" checked>
                                <label class="form-check-label" for="include-templates">模板管理</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="include-system" name="include_modules" value="system" checked>
                                <label class="form-check-label" for="include-system">系统状态</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">图表类型</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chart-pie" name="chart_types" value="pie" checked>
                                <label class="form-check-label" for="chart-pie">饼图</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chart-bar" name="chart_types" value="bar" checked>
                                <label class="form-check-label" for="chart-bar">柱状图</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chart-line" name="chart_types" value="line" checked>
                                <label class="form-check-label" for="chart-line">折线图</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="chart-table" name="chart_types" value="table" checked>
                                <label class="form-check-label" for="chart-table">数据表格</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">详细程度</label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" id="detail-summary" name="detail_level" value="summary" checked>
                                <label class="form-check-label" for="detail-summary">概要</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" id="detail-detailed" name="detail_level" value="detailed">
                                <label class="form-check-label" for="detail-detailed">详细</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" id="detail-comprehensive" name="detail_level" value="comprehensive">
                                <label class="form-check-label" for="detail-comprehensive">全面</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 报告历史 -->
<div class="row mb-4">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-history me-2"></i>报告历史
                    </h6>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="refreshReportHistory()">
                            <i class="fas fa-sync"></i>
                        </button>
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="clearReportHistory()">
                            <i class="fas fa-trash"></i> 清理
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="report-history" class="report-history">
                    <!-- 报告历史将动态加载 -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- 快速报告 -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-bolt me-2"></i>快速报告
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button type="button" class="btn btn-outline-primary" onclick="generateQuickReport('daily')">
                        <i class="fas fa-calendar-day"></i> 今日报告
                    </button>
                    <button type="button" class="btn btn-outline-success" onclick="generateQuickReport('weekly')">
                        <i class="fas fa-calendar-week"></i> 周报
                    </button>
                    <button type="button" class="btn btn-outline-info" onclick="generateQuickReport('monthly')">
                        <i class="fas fa-calendar-alt"></i> 月报
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="generateQuickReport('performance')">
                        <i class="fas fa-tachometer-alt"></i> 性能报告
                    </button>
                    <button type="button" class="btn btn-outline-danger" onclick="generateQuickReport('errors')">
                        <i class="fas fa-exclamation-triangle"></i> 错误报告
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 定时报告 -->
        <div class="card mt-3">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-clock me-2"></i>定时报告
                    </h6>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="addScheduledReport()">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="scheduled-reports" class="scheduled-reports">
                    <!-- 定时报告将动态加载 -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 报告预览模态框 -->
<div class="modal fade" id="reportPreviewModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">报告预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="report-preview-content">
                    <!-- 报告预览内容 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" onclick="downloadPreviewReport()">
                    <i class="fas fa-download"></i> 下载
                </button>
                <button type="button" class="btn btn-outline-primary" onclick="shareReport()">
                    <i class="fas fa-share"></i> 分享
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 定时报告设置模态框 -->
<div class="modal fade" id="scheduledReportModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">定时报告设置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="scheduled-report-form">
                    <div class="mb-3">
                        <label class="form-label">报告名称</label>
                        <input type="text" class="form-control" id="scheduled-name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">报告类型</label>
                        <select class="form-select" id="scheduled-type" name="report_type" required>
                            <option value="summary">系统概览</option>
                            <option value="usage">使用统计</option>
                            <option value="performance">性能分析</option>
                            <option value="error">错误分析</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">执行频率</label>
                        <select class="form-select" id="scheduled-frequency" name="frequency" required>
                            <option value="daily">每日</option>
                            <option value="weekly">每周</option>
                            <option value="monthly">每月</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">执行时间</label>
                        <input type="time" class="form-control" id="scheduled-time" name="time" value="09:00" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">输出格式</label>
                        <select class="form-select" id="scheduled-format" name="output_format" required>
                            <option value="pdf">PDF</option>
                            <option value="excel">Excel</option>
                            <option value="html">HTML</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮件接收者</label>
                        <input type="email" class="form-control" id="scheduled-email" name="email" placeholder="多个邮箱用逗号分隔">
                        <div class="form-text">留空则不发送邮件</div>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="scheduled-enabled" name="enabled" checked>
                        <label class="form-check-label" for="scheduled-enabled">
                            启用定时报告
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveScheduledReport()">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
.report-history {
    max-height: 400px;
    overflow-y: auto;
}

.report-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
}

.report-item:last-child {
    border-bottom: none;
}

.report-info {
    flex-grow: 1;
}

.report-title {
    font-weight: 500;
    color: #333;
    margin: 0;
}

.report-meta {
    color: #666;
    font-size: 12px;
    margin: 2px 0 0 0;
}

.report-actions {
    display: flex;
    gap: 5px;
}

.report-status {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}

.report-status.completed {
    background: #d4edda;
    color: #155724;
}

.report-status.processing {
    background: #d1ecf1;
    color: #0c5460;
}

.report-status.failed {
    background: #f8d7da;
    color: #721c24;
}

.scheduled-reports {
    max-height: 300px;
    overflow-y: auto;
}

.scheduled-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
}

.scheduled-item:last-child {
    border-bottom: none;
}

.scheduled-info {
    flex-grow: 1;
}

.scheduled-name {
    font-weight: 500;
    color: #333;
    margin: 0;
    font-size: 14px;
}

.scheduled-meta {
    color: #666;
    font-size: 11px;
    margin: 2px 0 0 0;
}

.scheduled-actions {
    display: flex;
    gap: 5px;
}

.empty-state {
    text-align: center;
    padding: 40px;
    color: #6c757d;
}

.empty-state i {
    font-size: 48px;
    margin-bottom: 15px;
    opacity: 0.5;
}

.report-preview-content {
    min-height: 400px;
    max-height: 600px;
    overflow-y: auto;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 20px;
    background: white;
}

.report-section {
    margin-bottom: 30px;
}

.report-section h3 {
    color: #333;
    border-bottom: 2px solid #007bff;
    padding-bottom: 5px;
    margin-bottom: 15px;
}

.report-chart {
    margin: 20px 0;
    text-align: center;
}

.report-table {
    width: 100%;
    border-collapse: collapse;
    margin: 15px 0;
}

.report-table th,
.report-table td {
    border: 1px solid #dee2e6;
    padding: 8px 12px;
    text-align: left;
}

.report-table th {
    background: #f8f9fa;
    font-weight: 500;
}

.report-metric {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
}

.report-metric:last-child {
    border-bottom: none;
}

.metric-label {
    color: #666;
}

.metric-value {
    font-weight: bold;
    color: #333;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let currentPreviewData = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeReportsPage();
});

// 初始化报告页面
function initializeReportsPage() {
    // 设置默认日期范围
    updateDateRange();
    
    // 加载报告历史
    loadReportHistory();
    
    // 加载定时报告
    loadScheduledReports();
    
    // 绑定事件
    bindEvents();
}

// 绑定事件
function bindEvents() {
    // 报告类型变化
    document.getElementById('report-type').addEventListener('change', updateReportOptions);
    
    // 时间范围变化
    document.getElementById('time-range').addEventListener('change', updateDateRange);
}

// 更新报告选项
function updateReportOptions() {
    const reportType = document.getElementById('report-type').value;
    const customOptions = document.getElementById('custom-options');
    
    if (reportType === 'custom') {
        customOptions.style.display = 'block';
    } else {
        customOptions.style.display = 'none';
    }
}

// 更新日期范围
function updateDateRange() {
    const timeRange = document.getElementById('time-range').value;
    const startDateContainer = document.getElementById('start-date-container');
    const endDateContainer = document.getElementById('end-date-container');
    const startDate = document.getElementById('start-date');
    const endDate = document.getElementById('end-date');
    
    if (timeRange === 'custom') {
        startDateContainer.style.display = 'block';
        endDateContainer.style.display = 'block';
    } else {
        startDateContainer.style.display = 'none';
        endDateContainer.style.display = 'none';
        
        // 设置预定义的日期范围
        const today = new Date();
        const endDateValue = today.toISOString().split('T')[0];
        
        let startDateValue;
        switch (timeRange) {
            case 'today':
                startDateValue = endDateValue;
                break;
            case 'yesterday':
                const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
                startDateValue = yesterday.toISOString().split('T')[0];
                endDate.value = startDateValue;
                break;
            case 'week':
                const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
                startDateValue = weekAgo.toISOString().split('T')[0];
                break;
            case 'month':
                const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
                startDateValue = monthAgo.toISOString().split('T')[0];
                break;
            case 'quarter':
                const quarterAgo = new Date(today.getTime() - 90 * 24 * 60 * 60 * 1000);
                startDateValue = quarterAgo.toISOString().split('T')[0];
                break;
            default:
                startDateValue = endDateValue;
        }
        
        startDate.value = startDateValue;
        if (timeRange !== 'yesterday') {
            endDate.value = endDateValue;
        }
    }
}

// 生成报告
function generateReport() {
    const formData = new FormData(document.getElementById('report-form'));
    
    // 添加自定义选项
    if (document.getElementById('report-type').value === 'custom') {
        const includeModules = [];
        document.querySelectorAll('input[name="include_modules"]:checked').forEach(cb => {
            includeModules.push(cb.value);
        });
        formData.append('include_modules', includeModules.join(','));
        
        const chartTypes = [];
        document.querySelectorAll('input[name="chart_types"]:checked').forEach(cb => {
            chartTypes.push(cb.value);
        });
        formData.append('chart_types', chartTypes.join(','));
        
        const detailLevel = document.querySelector('input[name="detail_level"]:checked')?.value;
        if (detailLevel) {
            formData.append('detail_level', detailLevel);
        }
    }
    
    CFS.utils.showLoading(true);
    
    fetch('/analytics/ajax/generate-report/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('报告生成成功', 'success');
            
            // 如果是HTML格式，显示预览
            if (formData.get('output_format') === 'html') {
                currentPreviewData = data;
                showReportPreview(data.content);
            } else {
                // 其他格式直接下载
                window.open(data.download_url);
            }
            
            // 刷新报告历史
            loadReportHistory();
        } else {
            CFS.utils.showNotification(data.message || '报告生成失败', 'error');
        }
    })
    .catch(error => {
        console.error('生成报告失败:', error);
        CFS.utils.showNotification('生成报告失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 预览报告
function previewReport() {
    const formData = new FormData(document.getElementById('report-form'));
    formData.set('output_format', 'html'); // 强制使用HTML格式预览
    
    // 添加自定义选项
    if (document.getElementById('report-type').value === 'custom') {
        const includeModules = [];
        document.querySelectorAll('input[name="include_modules"]:checked').forEach(cb => {
            includeModules.push(cb.value);
        });
        formData.append('include_modules', includeModules.join(','));
        
        const chartTypes = [];
        document.querySelectorAll('input[name="chart_types"]:checked').forEach(cb => {
            chartTypes.push(cb.value);
        });
        formData.append('chart_types', chartTypes.join(','));
        
        const detailLevel = document.querySelector('input[name="detail_level"]:checked')?.value;
        if (detailLevel) {
            formData.append('detail_level', detailLevel);
        }
    }
    
    CFS.utils.showLoading(true);
    
    fetch('/analytics/ajax/preview-report/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            currentPreviewData = data;
            showReportPreview(data.content);
        } else {
            CFS.utils.showNotification(data.message || '预览生成失败', 'error');
        }
    })
    .catch(error => {
        console.error('预览报告失败:', error);
        CFS.utils.showNotification('预览报告失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 显示报告预览
function showReportPreview(content) {
    document.getElementById('report-preview-content').innerHTML = content;
    const modal = new bootstrap.Modal(document.getElementById('reportPreviewModal'));
    modal.show();
}

// 下载预览报告
function downloadPreviewReport() {
    if (!currentPreviewData) {
        CFS.utils.showNotification('没有可下载的报告', 'warning');
        return;
    }
    
    const format = document.getElementById('output-format').value;
    const url = `/analytics/ajax/download-report/${currentPreviewData.report_id}/?format=${format}`;
    window.open(url);
}

// 分享报告
function shareReport() {
    if (!currentPreviewData) {
        CFS.utils.showNotification('没有可分享的报告', 'warning');
        return;
    }
    
    const shareUrl = `${window.location.origin}/analytics/reports/shared/${currentPreviewData.report_id}/`;
    
    if (navigator.share) {
        navigator.share({
            title: '分析报告',
            url: shareUrl
        });
    } else {
        // 复制到剪贴板
        navigator.clipboard.writeText(shareUrl).then(() => {
            CFS.utils.showNotification('分享链接已复制到剪贴板', 'success');
        }).catch(() => {
            prompt('复制分享链接:', shareUrl);
        });
    }
}

// 生成快速报告
function generateQuickReport(type) {
    const reportTypes = {
        'daily': { type: 'summary', range: 'today', format: 'html' },
        'weekly': { type: 'usage', range: 'week', format: 'pdf' },
        'monthly': { type: 'usage', range: 'month', format: 'excel' },
        'performance': { type: 'performance', range: 'week', format: 'html' },
        'errors': { type: 'error', range: 'week', format: 'html' }
    };
    
    const config = reportTypes[type];
    if (!config) return;
    
    // 设置表单值
    document.getElementById('report-type').value = config.type;
    document.getElementById('time-range').value = config.range;
    document.getElementById('output-format').value = config.format;
    
    // 更新选项
    updateReportOptions();
    updateDateRange();
    
    // 生成报告
    generateReport();
}

// 加载报告历史
function loadReportHistory() {
    fetch('/analytics/ajax/report-history/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderReportHistory(data.reports);
        }
    })
    .catch(error => {
        console.error('加载报告历史失败:', error);
    });
}

// 渲染报告历史
function renderReportHistory(reports) {
    const container = document.getElementById('report-history');
    
    if (!reports || reports.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-file-alt"></i>
                <p>暂无报告历史</p>
            </div>
        `;
        return;
    }
    
    const html = reports.map(report => {
        const statusClass = report.status === 'completed' ? 'completed' : 
                           report.status === 'processing' ? 'processing' : 'failed';
        
        return `
            <div class="report-item">
                <div class="report-info">
                    <div class="report-title">${report.name}</div>
                    <div class="report-meta">
                        ${report.type} | ${report.format.toUpperCase()} | ${CFS.utils.formatDateTime(report.created_at)}
                        <span class="report-status ${statusClass}">${getStatusText(report.status)}</span>
                    </div>
                </div>
                <div class="report-actions">
                    ${report.status === 'completed' ? `
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="downloadReport('${report.id}')">
                            <i class="fas fa-download"></i>
                        </button>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="viewReport('${report.id}')">
                            <i class="fas fa-eye"></i>
                        </button>
                    ` : ''}
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteReport('${report.id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
}

// 获取状态文本
function getStatusText(status) {
    const statusTexts = {
        'completed': '已完成',
        'processing': '处理中',
        'failed': '失败'
    };
    return statusTexts[status] || status;
}

// 下载报告
function downloadReport(reportId) {
    window.open(`/analytics/ajax/download-report/${reportId}/`);
}

// 查看报告
function viewReport(reportId) {
    window.open(`/analytics/reports/view/${reportId}/`, '_blank');
}

// 删除报告
function deleteReport(reportId) {
    if (!confirm('确定要删除这个报告吗？')) return;
    
    fetch(`/analytics/ajax/delete-report/${reportId}/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('报告已删除', 'success');
            loadReportHistory();
        } else {
            CFS.utils.showNotification(data.message || '删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('删除报告失败:', error);
        CFS.utils.showNotification('删除报告失败', 'error');
    });
}

// 刷新报告历史
function refreshReportHistory() {
    loadReportHistory();
}

// 清理报告历史
function clearReportHistory() {
    if (!confirm('确定要清理所有报告历史吗？此操作不可恢复。')) return;
    
    fetch('/analytics/ajax/clear-report-history/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('报告历史已清理', 'success');
            loadReportHistory();
        } else {
            CFS.utils.showNotification(data.message || '清理失败', 'error');
        }
    })
    .catch(error => {
        console.error('清理报告历史失败:', error);
        CFS.utils.showNotification('清理报告历史失败', 'error');
    });
}

// 加载定时报告
function loadScheduledReports() {
    fetch('/analytics/ajax/scheduled-reports/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderScheduledReports(data.reports);
        }
    })
    .catch(error => {
        console.error('加载定时报告失败:', error);
    });
}

// 渲染定时报告
function renderScheduledReports(reports) {
    const container = document.getElementById('scheduled-reports');
    
    if (!reports || reports.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-clock"></i>
                <p>暂无定时报告</p>
            </div>
        `;
        return;
    }
    
    const html = reports.map(report => {
        return `
            <div class="scheduled-item">
                <div class="scheduled-info">
                    <div class="scheduled-name">${report.name}</div>
                    <div class="scheduled-meta">
                        ${report.frequency} | ${report.time} | ${report.enabled ? '启用' : '禁用'}
                    </div>
                </div>
                <div class="scheduled-actions">
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="editScheduledReport('${report.id}')">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button type="button" class="btn btn-outline-${report.enabled ? 'warning' : 'success'} btn-sm" onclick="toggleScheduledReport('${report.id}', ${!report.enabled})">
                        <i class="fas fa-${report.enabled ? 'pause' : 'play'}"></i>
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteScheduledReport('${report.id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
}

// 添加定时报告
function addScheduledReport() {
    document.getElementById('scheduled-report-form').reset();
    const modal = new bootstrap.Modal(document.getElementById('scheduledReportModal'));
    modal.show();
}

// 编辑定时报告
function editScheduledReport(reportId) {
    fetch(`/analytics/ajax/scheduled-report/${reportId}/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const report = data.report;
            document.getElementById('scheduled-name').value = report.name;
            document.getElementById('scheduled-type').value = report.report_type;
            document.getElementById('scheduled-frequency').value = report.frequency;
            document.getElementById('scheduled-time').value = report.time;
            document.getElementById('scheduled-format').value = report.output_format;
            document.getElementById('scheduled-email').value = report.email || '';
            document.getElementById('scheduled-enabled').checked = report.enabled;
            
            // 设置报告ID用于更新
            document.getElementById('scheduled-report-form').dataset.reportId = reportId;
            
            const modal = new bootstrap.Modal(document.getElementById('scheduledReportModal'));
            modal.show();
        }
    })
    .catch(error => {
        console.error('加载定时报告失败:', error);
    });
}

// 保存定时报告
function saveScheduledReport() {
    const form = document.getElementById('scheduled-report-form');
    const formData = new FormData(form);
    const reportId = form.dataset.reportId;
    
    const url = reportId ? 
        `/analytics/ajax/scheduled-report/${reportId}/` : 
        '/analytics/ajax/scheduled-reports/';
    
    const method = reportId ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(reportId ? '定时报告已更新' : '定时报告已创建', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('scheduledReportModal'));
            modal.hide();
            
            // 清理表单
            form.reset();
            delete form.dataset.reportId;
            
            // 刷新列表
            loadScheduledReports();
        } else {
            CFS.utils.showNotification(data.message || '保存失败', 'error');
        }
    })
    .catch(error => {
        console.error('保存定时报告失败:', error);
        CFS.utils.showNotification('保存定时报告失败', 'error');
    });
}

// 切换定时报告状态
function toggleScheduledReport(reportId, enabled) {
    fetch(`/analytics/ajax/scheduled-report/${reportId}/toggle/`, {
        method: 'POST',
        body: JSON.stringify({ enabled: enabled }),
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(`定时报告已${enabled ? '启用' : '禁用'}`, 'success');
            loadScheduledReports();
        } else {
            CFS.utils.showNotification(data.message || '操作失败', 'error');
        }
    })
    .catch(error => {
        console.error('切换定时报告状态失败:', error);
        CFS.utils.showNotification('操作失败', 'error');
    });
}

// 删除定时报告
function deleteScheduledReport(reportId) {
    if (!confirm('确定要删除这个定时报告吗？')) return;
    
    fetch(`/analytics/ajax/scheduled-report/${reportId}/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('定时报告已删除', 'success');
            loadScheduledReports();
        } else {
            CFS.utils.showNotification(data.message || '删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('删除定时报告失败:', error);
        CFS.utils.showNotification('删除定时报告失败', 'error');
    });
}
</script>
{% endblock %}